<template>
    <div class="caseDetail">
        <div class="caseDetail_top">
			<div class="into_index">首页<i class="el-icon-close"></i></div>
			<div class="current">{{text}}<i class="el-icon-close"></i></div>
		</div>
		<div class="caseDetail_title">
			<div class="caseDetail_title_left">团队成员/<i>{{text}}</i></div>
			<div class="caseDetail_title_right">
				<button class="caseDetail_title_right_btn" @click="handerBase">返回</button>
			</div>
		</div>
        <!-- 内容 -->
        <div class="content">
            <el-tabs v-model="activeName" @tab-click="handleClick">
                <el-tab-pane label="户型信息" name="1">
                    <div class="houseInfo">
                        <div class="itemBox">
                            <span class="itemTit">地址</span>
                            <el-select v-model="provinceObj" @change="selectProvince" value-key="cityid" placeholder="请选择省份">
                                <el-option
                                v-for="item in province"
                                :key="item.cityid"
                                :label="item.city_name"
                                :value="{cityid:item.cityid,city_name:item.city_name}">
                                </el-option>
                            </el-select>
                            <el-select v-model="cityObj" @change="selectCity" value-key="cityid" placeholder="请选择城市">
                                <el-option
                                v-for="item in city"
                                :key="item.cityid"
                                :label="item.city_name"
                                :value="{cityid:item.cityid,city_name:item.city_name}">
                                </el-option>
                            </el-select>
                            <el-select v-model="districtObj" @change="selectDistrict" value-key="cityid" placeholder="请选择县区">
                                <el-option
                                v-for="item in district"
                                :key="item.cityid"
                                :label="item.city_name"
                                :value="{cityid:item.cityid,city_name:item.city_name}">
                                </el-option>
                            </el-select>
                            <!-- <el-input style="width:20%;" type="text" v-model="form.address" placeholder="请输入详细地址"></el-input> -->
                        </div>
                        <div class="itemBox">
                            <div class="item">
                                <span class="itemTit">面积</span>
                                <el-input style="width:26%;" type="number" v-model="form.area" placeholder="请输入面积"></el-input>m²
                            </div>
                            <div class="item">
                                <span class="itemTit">房型</span>
                                <el-input style="width:10%;" type="number" @blur="roomNum1" v-model="form.bedroom_num" placeholder=""></el-input>
                                室
                                <el-input style="width:10%;" type="number" @blur="roomNum2" v-model="form.parlour_num" placeholder=""></el-input>
                                厅
                            </div>
                        </div>
                        <div class="itemBox">
                            <div class="item">
                                <span class="itemTit">装修风格</span>
                                <el-select
                                    v-model="styleValue"
                                    multiple
                                    filterable
                                    allow-create
                                    default-first-option
                                    placeholder="请选择风格">
                                    <el-option
                                    v-for="item in styleList"
                                    :key="item.id"
                                    :label="item.name"
                                    :value="item.id">
                                    </el-option>
                                </el-select>
                            </div>
                            <div class="item">
                                <span class="itemTit">装修报价</span>
                                <el-input style="width:26%;" type="text" v-model="form.offer" placeholder="请输入报价"></el-input>万元
                            </div>
                        </div>
                    </div>
                </el-tab-pane>
                <el-tab-pane label="案例文章" name="2">
                    <div class="itemBox">
                        <div class="item">
                            <span class="itemTit">案例标题</span>
                            <el-input style="width:30%;" type="text" v-model="form.title" placeholder="请输入标题"></el-input>
                        </div>
                    </div>
                    <div class="itemBox">
                        <div class="item">
                            <span class="itemTit">轮播图</span>
                            <el-upload
                                action="/api/client/base/uploadfile"
                                list-type="picture-card"
                                :file-list="avatar"
                                :before-upload="beforeAvatarUpload"
                                :auto-upload="true"
                                :headers="myHeaders"
                                :on-success="handleAvatarSuccess"
                                :on-preview="handlePictureCardPreview"
                                accept="image/jpeg, image/jpg, image/gif, image/png"
                                :on-remove="handleRemove">
                                <i class="el-icon-plus"></i>
                            </el-upload>
                            <el-dialog :visible.sync="dialogVisible">
                                <img width="100%" :src="dialogImageUrl" alt="">
                            </el-dialog>
                        </div>
                    </div>
                    <div class="box">
                        <span class="itemTit">文章内容</span>
                        <div style="width:800px;height:400px;"><!--上传图片时得加载画面-->
                            <VueEditor style="width: 100%;height:300px" 
                                v-loading="editorLoading"
                                element-loading-text="图片上传中"
                                element-loading-background="rgba(0, 0, 0, 0.5)"
                                useCustomImageHandler 
                                @image-added="handleImageAdded"
                                :editorToolbar="customToolbar"
                                v-model="form.content">
                            </VueEditor>
                        </div>
                    </div>
                </el-tab-pane>
                <el-tab-pane label="点赞列表" name="3" v-if="case_id">
                    <div class="tit">共收到{{form.support_num}}个赞</div>
                    <el-table
                        :data="tabList"
                        height="250"
                        border
                        style="width: 100%">
                        <el-table-column
                        prop="id"
                        label="序号"
                        width="180">
                        </el-table-column>
                        <el-table-column
                        prop="nickname"
                        label="昵称"
                        width="180">
                        </el-table-column>
                        <el-table-column
                        prop="create_time"
                        :formatter="changeTime"
                        label="点赞时间">
                        </el-table-column>
                    </el-table>
                    <div class="sale_bottom_page_right">
                        <el-pagination
                            @size-change="handleSizeChange"
                            @current-change="handleCurrentChange"
                            :current-page="page"
                            :page-sizes="[10, 20, 30, 40]"
                            :page-size="pagesize"
                            layout="total, sizes, prev, pager, next, jumper"
                            :total="total"
                            background>
                        </el-pagination>
                    </div>
                </el-tab-pane>
                <el-tab-pane label="评论列表" name="4" v-if="case_id">
                    <div class="tit">共收到{{form.comment_num}}条评论</div>
                    <div class="commentItem" v-for="(item,index) in tabList" :key="index">
                        <div class="firstBox">
                            <div class="left">
                                <img :src="item.user_id.avatar?item.user_id.avatar.path:''" alt="">
                                <div class="cont">
                                    <div class="name">{{item.user_id.username}}</div>
                                    <div class="askCont">{{item.content}}</div>
                                </div>
                            </div>
                            <div class="right">
                                <div class="time">{{$moment(item.create_time*1000).format('yyyy-MM-DD HH:mm:ss')}}</div>
                                <div class="commentBtn">
                                    <el-button type="primary" size="mini" @click="toReply(item.id,item.user_id.username)">回复</el-button>
                                    <el-button type="danger" size="mini" @click="toDelReply(item.id)">删除</el-button>
                                </div>
                            </div>
                        </div>
                        <!-- 回复 -->
                        <div class="firstBox replyBox" v-for="(item1,index1) in item.sub_reply" :key="index1">
                            <div class="left">
                                <img :src="item1.user_id.avatar?item1.user_id.avatar.path:''" alt="">
                                <div class="cont">
                                    <div class="name">{{item1.user_id.username}}</div>
                                    <div class="askCont">
                                        <div class="ask_item">
                                            回复
                                            <span class="name" style="margin-left:5px">{{item1.reply_id.username}}</span>
                                            ：
                                        </div>
                                        {{item1.content}}
                                    </div>
                                </div>
                            </div>
                            <div class="right">
                                <div class="time">{{$moment(item1.create_time*1000).format('yyyy-MM-DD HH:mm:ss')}}</div>
                                <div class="commentBtn">
                                    <el-button type="primary" size="mini" @click="toReply(item1.id,item1.user_id.username)">回复</el-button>
                                    <el-button type="danger" size="mini" @click="toDelReply(item1.id)">删除</el-button>
                                </div>
                            </div>
                        </div>
                    </div>
                </el-tab-pane>
                <el-tab-pane label="转发列表" name="5" v-if="case_id">
                    <div class="tit">共转发{{form.forward_num}}次</div>
                    <el-table
                        :data="tabList"
                        height="250"
                        border
                        style="width: 100%">
                        <el-table-column
                        prop="id"
                        label="序号"
                        width="180">
                        </el-table-column>
                        <el-table-column
                        prop="nickname"
                        label="昵称"
                        width="180">
                        </el-table-column>
                        <el-table-column
                        prop="create_time"
                        :formatter="changeTime"
                        label="转发时间">
                        </el-table-column>
                    </el-table>
                    <div class="sale_bottom_page_right">
                        <el-pagination
                            @size-change="handleSizeChange"
                            @current-change="handleCurrentChange"
                            :current-page="page"
                            :page-sizes="[10, 20, 30, 40]"
                            :page-size="pagesize"
                            layout="total, sizes, prev, pager, next, jumper"
                            :total="total"
                            background>
                        </el-pagination>
                    </div>
                </el-tab-pane>
            </el-tabs>
        </div>
        
        <!-- 提交按钮 -->
        <div class="btn" v-if="activeName=='2'">
            <el-button type="primary" @click="toSubmit">提交</el-button>
        </div>
        <el-dialog
            title="回复内容"
            :visible.sync="dialogVisible_reply"
            width="30%">
            <div class="reply">
                <el-input type="textarea" rows="3" v-model="replyContent" :placeholder="replyUserName"></el-input>
            </div>
            <span slot="footer" class="dialog-footer">
                <el-button @click="dialogVisible_reply = false">取 消</el-button>
                <el-button type="primary" @click="toReplySubmit">确 定</el-button>
            </span>
        </el-dialog>
    </div>
</template>
<script>
import { VueEditor } from "vue2-editor";
export default {
    components:{
        VueEditor
    },
    data(){
        return{
            text:'案例详情',
            form:{
                address:'',
                area:'',
                bedroom_num:'',
                parlour_num:'',
                offer:'',
                title:'',
                content:'',
            },
            activeName:'1',
            provinceObj:{},
            cityObj:{},
            districtObj:{},
            province:[],
            city:[],
            district:[],
            styleList:[],//风格列表
            styleValue:[],//选择的风格
            myHeaders: {
              'access-token': this.$store.state.token  , //这里重新定义了请求头
              'Authorization': this.$store.state.token ,
              'user-id':this.$store.state.user_id
            },
            dialogImageUrl: '',
            dialogVisible: false,
            page:1,
            pagesize:10,
            total:0,
            avatar:[],
            tabList:[],//列表数据
            // fabulousData:[],//点赞列表数据
            // forwardData:[],//转发列表数据
            // commentData:[],//评论列表数据
            customToolbar:[
                [{'header':[false,1,2,3,4,5,6] }], //标题
                ['bold', 'italic', 'underline'],  //加粗\斜体\下划线
                ['italic'],  //斜体----也可以拆开来写，用于换位置顺序
                [{'align':''},{'align':'center'},{'align':'right'}], //对齐
                [{ 'list': 'ordered'}, { 'list': 'bullet' }, { 'list': 'check' }], //有序无序列表
                [{'background':[]},{'color':[]}], //背景色
                ['image','link'],  //图片、链接
                ['strike'],   //作废（文字中间一横）
                ['underline'],
                ['clean'],   //清楚格式（所谓去掉背景色这些花里胡巧）
                ['code'],  //代码
                ['code-block'], //代码块
                 //['video'] //视频
            ],
            editorLoading:false,
            sid:null,
            case_id:null, //案例id
            caseInfo:{},
            dialogVisible_reply:false,//回复弹出
            replyContent:'', //回复内容
            replyId:null, //评论id
            replyUserName:'',//回复的用户名字
        }
    },
    mounted() {
        this.sid = localStorage.getItem('sid')
        this.case_id = this.$route.query.case_id
        this.getStyleList()
        this.getProvince()
        if(this.case_id){
            this.getCaseInfo()
        }
    },
    methods:{
        handleClick(e){
            this.page = 1
            this.pagesize = 10
            this.total = 0
            if(e.name=='3' || e.name=='4' || e.name=='5'){
                this.getTabList()
            }
        },

        // 获取案例详情
        getCaseInfo(){
            let role = localStorage.getItem('role')
            let url = role=='decoration'?'/api/admin/decoration/BuildCase/view':'/api/admin/builder/BuildCase/view';
            this.$http.post(url,{id:this.case_id}).then(res=>{
                console.log(res,'案例详情');
                if(res.code==1){
                    this.form = res.data?res.data:{}
                    let styleArr = res.data.design_style.split(',')
                    styleArr.map(item=>{
                        this.styleValue.push(item*1)
                    })
                    console.log(this.styleValue,'风格项');
                    if(Array.isArray(res.data.thumb_url)){
                        res.data.thumb_url.map(item=>{
                            this.avatar.push({
                                id:item.id,
                                url:item.path
                            })
                        })
                    }else{
                        this.avatar.push({
                            id:res.data.thumb_url.id,
                            url:res.data.thumb_url.path
                        })
                    }

                    this.provinceObj = { //省
                        cityid:res.data.province_id?res.data.province_id:null,
                        city_name:res.data.province?res.data.province:'',
                    }
                    if(this.provinceObj){
                        this.getCity()
                    }
                    this.cityObj = { //市
                        cityid:res.data.city_id?res.data.city_id:null,
                        city_name:res.data.city?res.data.city:'',
                    }
                    if(this.cityObj){
                        this.getDistrict()
                    }
                    this.districtObj = { //区
                        cityid:res.data.district_id?res.data.district_id:null,
                        city_name:res.data.district?res.data.district:'',
                    }
                }
            })
        },


        // 提交按钮
        toSubmit(){
            let house_type = this.form.bedroom_num+'室'+this.form.parlour_num+'厅';
            let imgId = []
            this.avatar.map(item=>{
                if(item.response){
                    imgId.push(item.response.data.id)
                }else{
                    imgId.push(item.id)
                }
            })
            console.log(this.provinceObj);
            // let role = localStorage.getItem('role')
            let params = {
                // team_id:role=='decoration'?'':this.sid,
                // decoration_id:role=='decoration'?this.sid:'',
                // case_type:role=='decoration'?2:1,
                case_type:1,
                team_id:this.sid,
                id:this.case_id,
                title:this.form.title,
                address:this.form.address,
                content:this.form.content,
                bedroom_num:this.form.bedroom_num,
                parlour_num:this.form.parlour_num,
                house_type,
                thumb_url:imgId.join(','),
                area:this.form.area,
                offer:this.form.offer,
                design_style:this.styleValue.join(','),
                province:this.provinceObj.city_name,
                province_id:this.provinceObj.cityid,
                city:this.cityObj.city_name,
                city_id:this.cityObj.cityid,
                district:this.districtObj.city_name,
                district_id:this.districtObj.cityid
            }
            console.log(params,'案例新增数据');
            let url = this.case_id?'/api/admin/builder/BuildCase/edit':'/api/admin/builder/BuildCase/add';
            this.$http.post(url,params).then(res=>{
                console.log(res,'案例新增结果');
                if(res.code==1){
                    this.$message.success(this.case_id?'修改成功':'添加成功')
                    this.$router.back(1)
                }else{
                    this.$message.warning(res.msg)
                }
            })
        },

        // 删除评论
        toDelReply(id){
            this.$confirm('确定要删除该条评论吗？','提示',{
                confirmButtonText: "确定",
                cancelButtonText: "取消",
                type: "warning"
            }).then(()=>{
                this.$http.post('/api/admin/builder/CaseComment/del',{id}).then(res=>{
                    console.log(res,'删除结果');
                    if(res.code==1){
                        this.$message.success('删除成功')
                        this.getTabList()
                    }else{
                        this.$message.warning(res.msg)
                    }
                })
            })
        },

        roomNum1(e){
            console.log(e);
            let reg = /^[1-9]\d*$/
            console.log(reg.test(this.form.bedroom_num),'99999');
            if(!reg.test(this.form.bedroom_num)){
                this.$message.warning('最少为1哦~')
                this.form.bedroom_num = 1
            }
        },
        roomNum2(e){
            console.log(e);
            let reg = /^[1-9]\d*$/
            console.log(reg.test(ethis.form.parlour_num),'99999');
            if(!reg.test(this.form.parlour_num)){
                this.$message.warning('最少为1哦~')
                this.form.parlour_num = 1
            }
        },

        // 回复按钮
        toReply(id,name){
            this.replyId = id;
            this.replyUserName = '回复：'+name
            this.dialogVisible_reply = true
        },
        // 回复对话框确定
        toReplySubmit(){
            let params = {
                id:this.replyId,
                user_id:localStorage.getItem('user_id'),
                content:this.replyContent
            }
            console.log(params,'回复提交数据');
            this.$http.post('/api/admin/builder/CaseComment/reply',params).then(res=>{
                console.log(res,'回复结果');
                if(res.code==1){
                    this.$message.success('回复成功')
                    this.replyContent = ''
                    this.dialogVisible_reply = false
                    this.getTabList()
                }else{
                    this.$message.warning(res.msg)
                }
            })
        },

        // 选择省份
        selectProvince(){
            this.cityObj = {}
            this.districtObj = {}
            this.getCity()
        },

        // 选择城市
        selectCity(){
            this.districtObj = {}
            this.getDistrict()
        },

        // 选择县区
        selectDistrict(){

        },


        // 获取省份
        getProvince(){
        this.$http.post('/api/admin/base/Region/getProvinceList').then(res=>{
            console.log(res,'省份列表');
            if(res.code==1){
            this.province = res.data?res.data:[]
            }
        })
        },
        // 获取城市
        getCity(){
        this.$http.post('/api/admin/base/Region/getCityList',{province_id:this.provinceObj.cityid}).then(res=>{
            console.log(res,'城市列表');
            if(res.code==1){
            this.city = res.data?res.data:[]
            }
        })
        },
        // 获取县区
        getDistrict(){
        this.$http.post('/api/admin/base/Region/getDistrictList',{city_id:this.cityObj.cityid}).then(res=>{
            console.log(res,'县区列表');
            if(res.code==1){
            this.district = res.data?res.data:[]
            }
        })
        },

        // 获取点赞评论转发列表
        getTabList(){
            let params = {
                case_id:this.case_id,
                page:this.page,
                pagesize:this.pagesize
            }
            let url = this.activeName=='3'?'/api/admin/builder/CaseSupport/index':this.activeName=='4'?'/api/admin/builder/CaseComment/index':'/api/admin/builder/CaseForward/index'
            this.$http.post(url,params).then(res=>{
                console.log(res,'表格数据');
                if(res.code==1){
                    this.tabList = res.data.list?res.data.list:[]
                    this.total = res.data.total
                }
            })
        },
        
        // 获取风格列表
        getStyleList(){
            this.$http.post('/api/admin/base/option/getList').then(res=>{
                console.log(res,'风格列表');
                if(res.code==1){
                    this.styleList = res.data.design_style?res.data.design_style:[]
                }
            })
        },

        // 表格数据时间转换
        changeTime(row, column, cellValue, index){
            return this.$moment(cellValue*1000).format('yyyy-MM-DD hh:mm:ss')
        },

        // 返回
        handerBase(){
            this.$router.back(1)
        },

        handleRemove(file, fileList) {
            this.avatar = fileList
        },
        handlePictureCardPreview(file) {
            this.dialogImageUrl = file.url;
            this.dialogVisible = true;
        },
        handleAvatarSuccess(res, file,fileList) {
            this.avatar = fileList  
        },
        beforeAvatarUpload(file) {
            const isLt2M = file.size / 1024 / 1024 < 2;
            if (!isLt2M) {
                this.$message.error('上传商品图片大小不能超过 2MB!');
            }
            return isLt2M;
        },

        //富文本上传图片
        handleImageAdded(file, Editor, cursorLocation, resetUploader) {
            var formData = new FormData();
            let isLtSize = file.size / 1024 / 1024 < 2;
            // console.log(isLtSize);
            if (!isLtSize) {
                this.$message.warning("上传文件不能超过 2MB!");
                return;
            }
            this.editorLoading = true
            formData.append("file", file);
            console.log('666666666',formData);
            // this.$http
            //   .post("/api/client/base/uploadfile", formData)
            this.$api.uploadfile(formData)
            .then(result => {
                console.log(result);
                // 你上传路径返回的url
                let url = result.data.url;
                console.log(url);
                Editor.insertEmbed(cursorLocation, "image", url);
                resetUploader();
                this.editorLoading = false
            })
            .catch(err => {
                console.log(err);
                this.editorLoading = false
            });
        },
         handleSizeChange (val) {
            console.log(`每页 ${val} 条`);
            this.pagesize = val;
            this.getTabList()
        },
        handleCurrentChange (val) {
            console.log(`当前页: ${val}`);
            this.page = val
            this.getTabList()
        },
    }
}
</script>

<style lang='less'>
@import 'caseDetail.less';
</style>